package com.dayu.finecomm.dsc.handler;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;

import com.dayu.finecomm.dsc.DSCInterface;
import com.dayu.finecomm.dsc.DTUProxyManager;
import com.dayu.finecomm.dsc.net.DSCSocketServer;

/**
 * 监听socket事件处理
 * 
 * @author hddz
 * @since 2017-07-31 15:42:00
 * @version V1.0
 */
@Sharable
public class DSCTcpListen extends ChannelDuplexHandler {

	/**
	 * 监听Socket所在的TCP Server
	 */
	DSCSocketServer mServer = null;

	public DSCTcpListen(DSCSocketServer server) {
		mServer = server;
	}

	/**
	 * 有TCP连接进来
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// super.channelActive(ctx);

		ctx.pipeline().addLast(new DSCTcpHandler(mServer.getCallback()));
		DSCInterface callback = mServer.getCallback();
		callback.initChannel(ctx);
	}

	/**
	 * TCP连接断开
	 */
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		// 删除Channel Map中的失效Client
		String socket = ctx.channel().remoteAddress().toString();
		DTUProxyManager.getInstance().removeProxy(socket);
		ctx.close();
		ctx.fireChannelInactive();
	}

	/**
	 * 错误处理
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		String socket = ctx.channel().remoteAddress().toString();
		DTUProxyManager.getInstance().removeProxy(socket);
		ctx.close();
	}
}
